package com.yesorno.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.yesorno.activity.R;
import com.yesorno.constants.Constants;
import com.yesorno.model.HttpResponseObject;

public class HttpUtils {

	// http请求的默认编码
	private static String BASE_HTTP_ENCODE = Constants.BASE_HTTP_ENCODE;
	// 请求的最大尝试次数
	private static int MAX_RETRY = Constants.MAX_RETRY;

	private static HttpClient HTTPCLIENT = null;

	private static final int HTTP_TIMEOUT = 5 * 1000;

	private static final int SOCKET_TIMEOUT = 6 * 1000;

	private static final String ERROR_NET_STR = "{\"code\":-10,\"messages\":\"网络未连接或网络超时\",\"result\":{}}";

	private static Map<String, Bitmap> YESORNO_BITMAP_CACHE = new HashMap<String, Bitmap>();

	public static void putBitmapToCache(String key, Bitmap value) {
		YESORNO_BITMAP_CACHE.put(key, value);
	}

	public static Bitmap getBitmapFromCache(String key) {
		Log.i("缓存获取图片", key);
		return YESORNO_BITMAP_CACHE.get(key);
	}

	/**
	 * 根据url返回该图片的bitmap封装的对象
	 * 
	 * @param url
	 * @return
	 */
	public static Bitmap returnBitMap(Context context, String url) {
		// TODO 这里是临时搞假数据用的，将来要换掉
		if (url.indexOf("common_type_logo.jpg") > -1) {
			return BitmapUtils.getBitmapFromResource(context,
					R.drawable.common_type_logo);
		}
		if (url.indexOf("mm") > -1) {
			return BitmapUtils.getBitmapFromResource(context, R.drawable.mm);
		}
		return null;
		// URL myFileUrl = null;
		// Bitmap bitmap = getBitmapFromCache(url);
		// if (url == null || url.trim().length() == 0 || url.equals("null")) {
		// return null;
		// }
		// if (bitmap == null) {
		// try {
		// myFileUrl = new URL(url);
		// } catch (MalformedURLException e) {
		// e.printStackTrace();
		// }
		// try {
		// HttpURLConnection conn = (HttpURLConnection) myFileUrl
		// .openConnection();
		// conn.setDoInput(true);
		// conn.setConnectTimeout(HTTP_TIMEOUT);// 超时
		// conn.connect();
		// Log.i("获取网络图片", url);
		// if (conn.getResponseCode() != 200) {// 请求失败或超时
		// throw new RuntimeException("请求url失败");
		// } else {
		// InputStream is = conn.getInputStream();
		// bitmap = BitmapFactory.decodeStream(is);
		// is.close();
		// }
		// putBitmapToCache(url, bitmap);
		// } catch (IOException e) {
		// e.printStackTrace();
		// }
		// }
		// return bitmap;
	}

	/**
	 * 验证文本是否与正则匹配
	 * 
	 * @param reg
	 * @param testStr
	 * @return
	 */
	public static boolean isMatch(String reg, String testStr) {
		Pattern pattern = Pattern.compile(reg);
		Matcher matcher = pattern.matcher(testStr);
		return matcher.matches();
	}

	/**
	 * 判断是否是空字符串
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEmptyString(String str) {
		return str == null || str.trim().length() == 0;
	}

	/**
	 * 通过http请求获取内容
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public static HttpResponseObject getInfoFromUrl(String url,
			Map<String, Object> params) {
		if (!url.endsWith("?")) {
			url += "?";
		}
		Iterator<String> it = params.keySet().iterator();
		boolean isFirst = true;
		while (it.hasNext()) {
			String key = it.next();
			Object val = params.get(key);
			if (isFirst) {
				isFirst = false;
			} else {
				url += "&";
			}
			url += key + "=" + val.toString();
		}
		return getInfoFromUrl(url, BASE_HTTP_ENCODE);
	}

	/**
	 * 模拟的假数据，不发请求
	 * 
	 * @param url
	 * @return
	 */
	private static HttpResponseObject getHtml(String url) {
		String result = "";
		int temp = -1;
		if (url.indexOf(Constants.USER_LOGIN_URL) > temp) {
			result = "{code:0,messages:\"sd\",\"result\":{\"userId\":101,\"Showname\":\"\u75af\u72c2\u7684\u7334\u5b50\",\"Avtar\":null,\"State\":1}}";
		}
		if (url.indexOf(Constants.USER_CATEGORY_LIST_URL) > temp) {
			result = "{code:1,messages:\"ok\",result:{list:[{id:\"1\",name:\"衣服1\",isSelect:true},{id:\"2\",name:\"衣服2\",isSelect:true},{id:\"3\",name:\"衣服3\",isSelect:true},{id:\"4\",name:\"衣服4\",isSelect:true},{id:\"5\",name:\"衣服5\",isSelect:true},{id:\"6\",name:\"衣服6\",isSelect:true},{id:\"7\",name:\"衣服7\",isSelect:true},{id:\"8\",name:\"衣服8\",isSelect:false},{id:\"9\",name:\"衣服9\",isSelect:true}]}}";
		}
		if (url.indexOf(Constants.HALL_LIST_URL) > temp) {
			result = "{code:1,messages:\"ok\",result:{list:[{userId:100,topicId:55,from:1,countYes:45,countNo:20,userName:\"大宝\",publishTime:\"3分钟前\",desc:\"一些说明的无聊\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",img:null},{userId:101,topicId:56,from:0,countYes:42,countNo:21,userName:\"自己\",publishTime:\"1分钟前\",desc:\"一些说明的无聊\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",img:\"http://172.16.16.94:8080/img/common_type_logo.jpg\"}]}}";
		}
		if (url.indexOf(Constants.TOPIC_DETAIL_URL) > temp) {
			result = "{code:1,messages:\"ok\",result:{topic:{topicId:1,isCommentYes:true,isCommentNo:false,authorLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",authorId:1,authorName:\"小明\",desc:\"图片图片看一看，好无聊的图片图片图片看一看，好无聊的图片图片图片看一看，好无聊的图片图片图片看一看，好无聊的图片图片图片看一看，好无聊的图片图片图片看一看\",imgs:\"http://172.16.16.94:8080/img/mm.jpg\",title:\"美图的标题\",yesCount:10,noCount:5,from:\"android客户端\",publishTime:\"2011-09-08 12:12\"}}}";
		}
		if (url.indexOf(Constants.COMMENT_LIST_URL) > temp) {
			result = "{code:1,messages:\"ok\",result:{list:[{userName:\"小明\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",editTime:\"2011-09-12 12:12\",desc:\"不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错\",userId:100,commentType:1},{userName:\"自己\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",editTime:\"2011-09-12 12:12\",desc:\"不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错\",userId:101,commentType:0},{userName:\"2明\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",editTime:\"2011-09-12 12:12\",desc:\"不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错\",userId:100,commentType:1},{userName:\"3明\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",editTime:\"2011-09-12 12:12\",desc:\"不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错不错\",userId:100,commentType:0}]}}";
		}
		if (url.indexOf(Constants.USER_INFO_URL) > temp) {
			result = "{code:1,messages:\"ok\",result:{user:{userName:\"小明\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",sex:1,desc:\"无聊发呆中\",publicTopicCounts:10,attentionCounts:20,joinTopicCounts:30,fansCounts:50,isAttention:false}}}";
		}
		if (url.indexOf(Constants.BLACK_LIST_URL) > temp) {
			result = "{code:1,messages:\"ok\",result:{blacklist:[{userName:\"小明\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",userId:100},{userName:\"小李\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",userId:104}]}}";
		}
		if (url.indexOf(Constants.TOPIC_PUBLIC_LIST_URL) > temp) {
			result = "{code:1,messages:\"ok\",result:{topicList:[{userId:100,topicId:55,from:1,countYes:45,countNo:20,userName:\"大宝\",publishTime:\"3分钟前\",desc:\"一些说明的无聊\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",img:null},{userId:101,topicId:56,from:0,countYes:42,countNo:21,userName:\"自己\",publishTime:\"1分钟前\",desc:\"一些说明的无聊\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",img:\"http://172.16.16.94:8080/img/common_type_logo.jpg\"}]}}";
		}
		if (url.indexOf(Constants.TOPIC_JOIN_LIST_URL) > temp) {
			result = "{code:1,messages:\"ok\",result:{topicList:[{userId:100,topicId:55,from:1,countYes:45,countNo:20,userName:\"大宝\",publishTime:\"3分钟前\",desc:\"一些说明的无聊\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",img:null},{userId:101,topicId:56,from:0,countYes:42,countNo:21,userName:\"自己\",publishTime:\"1分钟前\",desc:\"一些说明的无聊\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",img:\"http://172.16.16.94:8080/img/common_type_logo.jpg\"}]}}";
		}
		if (url.indexOf(Constants.ATTENTION_LIST_URL) > temp) {
			result = "{code:1,messages:\"ok\",result:{list:[{userId:100,userName:\"小明\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",isAttention:true},{userId:102,userName:\"小李\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",isAttention:false}]}}";
		}
		if (url.indexOf(Constants.FANS_LIST_URL) > temp) {
			result = "{code:1,messages:\"ok\",result:{list:[{userId:100,userName:\"小明2\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",isAttention:true},{userId:102,userName:\"小李2\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",isAttention:false}]}}";
		}
		if (url.indexOf(Constants.USER_MESSAGE_LIST_URL) > temp) {
			result = "{code:1,messages:\"ok\",result:{list:[{userId:100,publishTime:\"09-11 20:20\",desc:\"无聊的消息\",userName:\"小明\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",messageId:2},{userId:102,publishTime:\"09-11 20:20\",desc:\"无聊的消息\",userName:\"小李2\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",messageId:2},{userId:103,publishTime:\"09-11 20:20\",desc:\"无聊的消息3\",userName:\"小李3\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",messageId:3}]}}";
		}
		if (url.indexOf(Constants.USER_VIEWMESSAGE_LIST_URL) > temp) {
			result = "{code:1,messages:\"ok\",result:{list:[{userId:100,publishTime:\"09-11 20:20\",desc:\"无聊的消息\",userName:\"小明\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",messageId:2},{userId:102,publishTime:\"09-11 20:20\",desc:\"无聊的消息\",userName:\"小李2\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",messageId:2},{userId:103,publishTime:\"09-11 20:20\",desc:\"无聊的消息3\",userName:\"小李3\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",messageId:3}]}}";
		}
		if (url.indexOf(Constants.USER_COMMENT_LIST_URL) > temp) {
			result = "{code:1,messages:\"ok\",result:{list:[{userId:101,editTime:\"09-11 20:20\",desc:\"无聊的消息2\",userName:\"小明\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",commentId:2,topicId:1,topicName:\"小明的爸爸有3个儿子，老大叫大名，老二叫二明，老三叫什么\",commentType:1},{userId:101,editTime:\"09-11 20:20\",desc:\"无聊的消息\",userName:\"小李\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",commentId:1,topicId:1,topicName:\"小明的爸爸有3个儿子，老大叫大名，老二叫二明，老三叫什么\",commentType:0}]}}";
		}
		if (url.indexOf(Constants.PERSONAL_MESSAGE_RECALL_URL) > temp) {
			result = "{code:1,messages:\"ok\",result:{list:[{userId:101,editTime:\"09-11 20:20\",desc:\"无聊的消息2\",userName:\"小明\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",commentId:2,topicId:1,topicName:\"小明的爸爸有3个儿子，老大叫大名，老二叫二明，老三叫什么\",commentType:1},{userId:101,editTime:\"09-11 20:20\",desc:\"无聊的消息\",userName:\"小李\",userLogo:\"http://172.16.16.94:8080/img/common_type_logo.jpg\",commentId:1,topicId:1,topicName:\"小明的爸爸有3个儿子，老大叫大名，老二叫二明，老三叫什么\",commentType:0}]}}";
		}

		return result.trim().length() == 0 ? null : getFromJson(result);
	}

	/**
	 * 通过http请求获取内容
	 * 
	 * @param url
	 *            请求地址
	 * @param requestType
	 *            请求方式(post,get)
	 * @return
	 */
	public static HttpResponseObject getInfoFromUrlByMethod(String url,
			String requestType, Context context) {
		HttpResponseObject result = null;
		if (requestType.equals(Constants.HTTP_REQUEST_GET)) {
			result = getInfoByUrlGet(url, context);
		}
		if (requestType.equals(Constants.HTTP_REQUEST_POST)) {
			result = getInfoByUrlPost(url, context);
		}
		return result;
	}

	public static boolean judgeNetConnect(Context context) {
		ConnectivityManager mConnectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		TelephonyManager mTelephony = (TelephonyManager) context
				.getSystemService(Activity.TELEPHONY_SERVICE);
		// 检查网络连接，如果无网络可用，就不需要进行连网操作等
		NetworkInfo info = mConnectivity.getActiveNetworkInfo();
		if (info == null || !mConnectivity.getBackgroundDataSetting()) {
			return false;
		}
		Log.d("network", "NetworkInfo" + info.isConnectedOrConnecting());
		// 判断网络连接类型，只有在3G或wifi里进行一些数据更新。
		int netType = info.getType();
		// int netSubtype = info.getSubtype();
		if (netType == ConnectivityManager.TYPE_WIFI) {
			return info.isConnected();
		} else if (netType == ConnectivityManager.TYPE_MOBILE
		// && netSubtype ==
		// TelephonyManager.NETWORK_TYPE_UMTS//这行是用来严格判断当前的sim卡类型的，具体参见http://yuanliyin.iteye.com/blog/665523
				&& !mTelephony.isNetworkRoaming()) {
			return info.isConnected();
		} else {
			return false;
		}
	}

	/**
	 * 通过http请求获取内容（post请求）
	 * 
	 * @param urls
	 * @param context
	 * @return
	 */
	public static HttpResponseObject getInfoByUrlPost(String urls,
			Context context) {
		if (!judgeNetConnect(context)) {
			return getFromJson(ERROR_NET_STR);
		}
		// TODO 这里是临时搞假数据用的，将来要换掉
		return getHtml(urls);
		// int state = 0;
		// String strResult = "";
		// HttpPost httpost = new HttpPost(getReqPathFromUrls(urls));
		//
		// BasicHttpParams httpParameters = new BasicHttpParams();
		// // Set the default socket timeout (SO_TIMEOUT)
		// HttpConnectionParams.setConnectionTimeout(httpParameters,
		// HTTP_TIMEOUT);
		// // in milliseconds which is the timeout for waiting for data.
		// HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIMEOUT);
		// // 取得HttpClient对象
		// if (HTTPCLIENT == null) {
		// HTTPCLIENT = new DefaultHttpClient(httpParameters);
		// }
		// // 请求HttpClient，取得HttpResponse
		// HttpResponse httpResponse;
		// try {
		// httpost.setEntity(new UrlEncodedFormEntity(getParmasList(urls),
		// HTTP.UTF_8));
		// httpResponse = HTTPCLIENT.execute(httpost);
		//
		// // 请求成功
		// if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
		// {
		// // 取得返回的字符串
		// strResult = EntityUtils.toString(httpResponse.getEntity());
		// httpost.abort();
		// } else {
		// state = 1;
		// }
		// } catch (Exception e) {
		// state = 1;
		// Log.e("getInfoByUrl", e.getMessage());
		// }
		// if (state == 1) {
		// return getFromJson(ERROR_NET_STR);
		// }
		// return strResult.trim().length() == 0 ? null :
		// getFromJson(strResult);
	}

	private static HttpResponseObject getFromJson(String strResult) {
		JSONObject jsonObject;
		HttpResponseObject httpResponseObject = new HttpResponseObject();
		try {
			jsonObject = new JSONObject(strResult);
			httpResponseObject.setCode(jsonObject.getInt("code"));
			httpResponseObject.setMessages(jsonObject.getString("messages"));
			httpResponseObject.setResult((JSONObject) jsonObject.get("result"));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return httpResponseObject;
	}

	/**
	 * 通过url分析出请求地址
	 * 
	 * @param urls
	 * @return
	 */
	private static String getReqPathFromUrls(String urls) {
		return urls.substring(0, urls.indexOf("?"));
	}

	/**
	 * 通过url分析出参数的串
	 * 
	 * @param urls
	 * @return
	 */
	private static String getParamsFromUrls(String urls) {
		return urls.substring(urls.indexOf("?") + 1, urls.length());
	}

	/**
	 * 根据url生成post提交用的list
	 * 
	 * @param urls
	 * @return
	 */
	private static List<NameValuePair> getParmasList(String urls) {
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		String params = getParamsFromUrls(urls);
		String[] arr = params.split("&");
		for (int i = 0; i < arr.length; i++) {
			String temp = arr[i];
			int startTemp = temp.indexOf("=");
			nvps.add(new BasicNameValuePair(temp.substring(0, startTemp), temp
					.substring(startTemp + 1, temp.length())));
		}
		return nvps;
	}

	/**
	 * 通过http请求获取内容（get请求）
	 * 
	 * @param urls
	 * @param context
	 * @return
	 */
	public static HttpResponseObject getInfoByUrlGet(String urls,
			Context context) {
		if (!judgeNetConnect(context)) {
			return getFromJson(ERROR_NET_STR);
		}
		int state = 0;
		String strResult = "";
		HttpGet httpget = new HttpGet(urls);
		// 取得HttpClient对象
		if (HTTPCLIENT == null) {
			HTTPCLIENT = new DefaultHttpClient();
		}
		// 请求HttpClient，取得HttpResponse
		HttpResponse httpResponse;
		try {
			httpResponse = HTTPCLIENT.execute(httpget);
			// 请求成功
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				// 取得返回的字符串
				strResult = EntityUtils.toString(httpResponse.getEntity());
				httpget.abort();
			} else {
				state = 1;
			}
		} catch (Exception e) {
			state = 1;
			Log.e("getInfoByUrl", e.getMessage());
		}
		if (state == 1) {
			return null;
		}
		return strResult.trim().length() == 0 ? null : null;
	}

	/**
	 * 通过http请求获取内容(目前未用)
	 * 
	 * @param url
	 * @param encode
	 * @return
	 */
	public static HttpResponseObject getInfoFromUrl(String url, String encode) {
		if (encode == null || encode.trim().length() == 0) {
			encode = BASE_HTTP_ENCODE;
		}
		StringBuilder sb = new StringBuilder();
		int retry = MAX_RETRY;
		int state = 0;
		HttpURLConnection httpConnection = null;
		while (retry > 0) {
			try {
				httpConnection = (HttpURLConnection) new URL(url)
						.openConnection();
				httpConnection.setRequestMethod("GET");
				httpConnection.connect();
				int num = MAX_RETRY - retry + 1;
				Log.i("getInfoFromUrl", "第" + num + "次获取 \"" + url + "\" 信息");
				int code = httpConnection.getResponseCode();
				if (code == HttpURLConnection.HTTP_OK) {
					BufferedReader in = new BufferedReader(
							new InputStreamReader(
									httpConnection.getInputStream(), encode));
					while (in.ready()) {
						sb.append(in.readLine());
					}
					break;
				}
			} catch (MalformedURLException e) {
				Log.e("getInfoFromUrl", url + "不合法\n" + e.getMessage());
				state = 1;
				break;
			} catch (UnsupportedEncodingException e) {
				Log.e("getInfoFromUrl", url + "[" + encode + "]"
						+ "不支持的encoding\n" + e.getMessage());
				state = 1;
				break;
			} catch (Exception e) {
				Log.e("getInfoFromUrl", e.getMessage());
				state = 2;
				break;
			} finally {
				retry--;
			}
		}
		httpConnection.disconnect();
		String strResult = sb.toString();
		if (state == 1) {
			return null;
		}
		return strResult.trim().length() == 0 ? null : null;
	}
}
